/** @format */

import React, {Component} from 'react';

import styles from '../Styles/main';
import SearchResult from './SearchResult.js'
import Icons from '../Assets/Icon.js'

import {
  Text,
  View,
  NavigatorIOS,
  TextInput,
  ActivityIndicator,
  ListView,
  TouchableHighlight,
  Image,
  AsyncStorage,
} from 'react-native';

class SearchForm extends React.Component {
  constructor(props) {
    super(props);

    this.dataSource = new ListView.DataSource({
      rowHasChanged: (row1, row2) => row1 !== row2
    });

    this.state = {
      query : '',
      loaded:true,
      opacity: 0,
      searchHistory: [],
    }

    AsyncStorage.getItem('searchHistory')
      .then((searchHistory) => {
        if(searchHistory) {
          this.setState({
            searchHistory: JSON.parse(searchHistory)
          })
        }
      })
  }

  searchHistory() {
    let newSearchHistory = [...new Set([this.state.query, ...this.state.searchHistory])];

    this.setState({
      searchHistory: newSearchHistory
    });

    AsyncStorage.setItem('searchHistory', JSON.stringify(newSearchHistory));
  }

  fetchData() {

    this.setState({
      loaded:false,
      opacity:1,
    });

    this.searchHistory();

    const REQUEST_URL = `https://api.douban.com/v2/movie/search?q=${this.state.query}`
    fetch(REQUEST_URL)
      .then(response => response.json())
      .then(responseData => {
        //console.log(responseData);
        this.props.navigator.push({
          title: responseData.title,
          component: SearchResult,
          passProps: {
            results: responseData,
            query: this.state.query
          }
        });

        this.setState({
          loaded:true,
          opacity:0,
        });
      })
      .done();
  }

  async search(item) {
    try{
      await this.setState({
        query: item,
      });

      this.fetchData();
    } catch(error) {
      console(error)
    }

  }

  deleteSearchHistory(item) {
      console.log('bdl');
      console.log(item);
      let newSearchHistory = new Set(this.state.searchHistory);
      newSearchHistory.delete(item);
      this.setState({
        searchHistory: [...newSearchHistory],
      });

      AsyncStorage.setItem(
        'searchHistory', JSON.stringify([...newSearchHistory])
      )
  }

  renderSearchList(item) {
    return (
      <TouchableHighlight
        underlayColor="rgba(34,26,38,0.1)"
        onPress={()=>this.search(item)}
      >
        <View style={styles.item}>
          <TouchableHighlight
            underlayColor="rgba(34,26,38,0.1)"
            onPress={()=>this.deleteSearchHistory(item)}
          >
            <Image
              source={{uri: Icons.delete}}
              style={styles.deleteIcon}
            />
          </TouchableHighlight>
          <View style={styles.itemContent}>
            <Text style={styles.itemHeader}>{item}</Text>
          </View>
        </View>
      </TouchableHighlight>
    )
  }

  render() {
    return (
      <View style={[styles.container],{paddingTop: 60}}>
        <View style={{
          paddingTop: 7,
          paddingLeft: 7,
          paddingRight: 7,
          borderColor: "rgba(100,53,201,0.1)",
          borderBottomWidth:1,
        }}>
          <TextInput
            style={{height:50}}
            placeholder='搜索 ...'
            placeholderTextColor="#6435c9"
            clearButtonMode="while-editing"
            clearTextOnFocus={true}
            value={this.state.query}
            autoFocus
            autoCorrect={false}
            returnKeyType="search"
            onFocus={ () => console.log('onFocus')}
            onChangeText={ (query) => (
              //console.log(text),
              this.setState({
                query
              })
            )}
            onSubmitEditing={this.fetchData.bind(this)}
          />

          <ActivityIndicator
            size="small"
            color="#6435c9"
            animating={!this.state.loaded}
            style={{
              position: 'absolute',
              right: 10,
              top:20,
              opacity: this.state.opacity
            }}

          />
        </View>
        <Text style={styles.searchHeader}>搜索历史</Text>

        <ListView
          dataSource={this.dataSource.cloneWithRows(
            this.state.searchHistory
          )}
          renderRow={this.renderSearchList.bind(this)}
        />
      </View>
    );

  }
}

export {SearchForm as default}
